const axios = require("axios");
const { TOKEN_URL, BotUrl, TOKEN_PARAMS } = require("./configs/chatConfig");
const { setCache, getCache } = require("./utils/cache");
const { scheduler } = require("./schedule/schedule");
class Conversation {
  constructor() {
    // 上下文数据存在这里，文心的调用是需要把所有的历史对话数据全部传过去，所以上下文窗口大小得注意
    this.messages = [];
    this.init();
  }
  init() {
    // 添加定时任务  每隔25天进行重新请求获取新token
    scheduler.addTask("getWenXinYiYanToken", "0 0 0 */25 * *", async () => {
      console.log(
        "定时任务获取智能机器人token执行！当前时间：",
        new Date().toLocaleTimeString()
      );
      this.getToken();
    });
    this.getToken();
  }
  async getToken() {
    try {
      let token = getCache("Token.json", "BotToken");
      if (!token) {
      } else {
        return token;
      }
      const params = TOKEN_PARAMS;
      const res = await axios.post(
        `${TOKEN_URL}?${new URLSearchParams(params)}`
      );
      const secondsInADay = 24 * 60 * 60; // 一天有 24 小时 * 60 分钟 * 60 秒

      const days = 25;
      const seconds = days * secondsInADay;
      const { access_token } = res.data;
      setCache("Token.json", "BotToken", access_token, seconds);
      return access_token;
    } catch (error) {
      return "";
    }
  }
  async ask(prompt) {
    const accessToken = await this.getToken();
    if (!accessToken) return "请联系管理员";
    // 问句push进去
    this.messages.push({ role: "user", content: prompt });
    console.log("message" + this.messages[0]);
    try {
      const res = await axios.post(
        BotUrl,
        { messages: this.messages },
        { params: { access_token: accessToken } }
      );
      const { data } = res;
      console.log("智能机器人返回数据", data);
      // 答案也放进去
      this.messages.push({ role: "assistant", content: data.result });
      return data.result;
    } catch (error) {
      console.log("调用智能机器模型失败" + error);
    }
  }
}
const conversation = new Conversation();
module.exports = {
  conversation,
};
